import asyncio
import random

"""
在同一个协程及其链路上 我们要求其数据保持一致
"""

class Data(object):

    def __init__(self):
        self.item = None

    def set(self, item):
        self.item = item

    def get(self):
        return self.item


request_id = Data()


async def some_inner_coroutine(req_id):
    # get value
    await asyncio.sleep(random.uniform(0, 1))
    print('Processed inner coroutine of request[req_id]: {} - {}'.format(req_id, request_id.get()))


async def some_outer_coroutine(req_id):
    # set value
    request_id.set(req_id)

    await some_inner_coroutine(req_id)

    # get value
    print('Processed outer coroutine of request: {}'.format(request_id.get()))


async def main():
    tasks = []
    for req_id in range(1, 5):
        tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))

    await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())
